package com.hnxxxy.common.shiro.filter;

import com.alibaba.fastjson.JSONObject;
import com.hnxxxy.sysmgr.pojo.Staff;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @CLASSDESCRIPER:
 * @AUTHOR:suhui
 * @PHONE:13319575368
 * @EMIAL:13319575368@163.COM
 * @DATE: 2020/5/12
 * @PARAMDESCRIPER:
 * @OUTPARAMDESCRIPER:
 */
@Slf4j
public class CheckSessionControlFilter extends AccessControlFilter {
    private String kickoutUrl="/?msg=1"; //踢出后到的地址
    private boolean kickoutAfter = false; //踢出之前登录的/之后登录的用户 默认踢出之前登录的用户
    private int maxSession = 1; //同一个帐号最大会话数 默认1
    @Setter
    private SessionManager sessionManager;
    @Setter
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = getSubject(request, response);
        if (!subject.isAuthenticated() && !subject.isRemembered()) {
            return true;
        }
        Session session = subject.getSession();
        Staff user = (Staff) subject.getPrincipal();
        String username = user.getLoginname();
        Serializable sessionId = session.getId();

        Deque<Serializable> deque=null;
        Object o=redisTemplate.opsForValue().get("Deque:" + username);
        if(o!=null){
            deque = (Deque<Serializable>)o;
        }
        if (deque == null) {
            deque = new LinkedList<Serializable>();
            deque.push(sessionId);
            redisTemplate.opsForValue().set("Deque:" + username,deque);
            //return true;
        }
        //如果队列里没有此sessionId，且用户没有被踢出；放入队列
        if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) {
            //将sessionId存入队列
            deque.push(sessionId);
        }

        //如果队列里的sessionId数超出最大会话数，开始踢人
        Session kickoutSession = null;
        while (deque.size() > maxSession) {
            Serializable kickoutSessionId = null;
            if (kickoutAfter) { //如果踢出后者
                kickoutSessionId = deque.removeFirst();
            } else { // 否则踢出前者
                kickoutSessionId = deque.removeLast();
            }
            redisTemplate.opsForValue().set("Deque:" + username,deque);
            try{
                DefaultSessionKey sessionKey = new DefaultSessionKey(kickoutSessionId);
                kickoutSession= sessionManager.getSession(sessionKey);
                if (kickoutSession != null) {
                    // 设置会话的kickout属性表示踢出了
                    kickoutSession.setAttribute("kickout", false);
                }
            }catch (UnknownSessionException e){
                    log.info("-->kickoutSessionId已经失效,deque进行释放,此异常可以忽略");
            }


        }

        //如果被踢出了，直接退出，重定向到踢出后的地址

        if (session.getAttribute("kickout") != null &&!((Boolean) session.getAttribute("kickout"))) {
            try {
                subject.logout();
            } catch (Exception e) { //ignore
            }
            saveRequest(request);
            Map<String, String> resultMap = new HashMap<String, String>();
            // 判断是不是Ajax请求
            if ("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {
                resultMap.put("user_status", "300");
                resultMap.put("message", "您已经在其他地方登录，请重新登录！");
                // 输出json串
                out(response, resultMap);
            } else {
                // 重定向
                request.setAttribute("msg","您已经在其他地方登录，请重启登录");
                WebUtils.issueRedirect(request, response, kickoutUrl);
            }
            return false;
        }
        return Boolean.TRUE;

    }


    /**
     * @Description:
     * @Author: SUHUI
     * @EMAIL:13319575368@163.COM
     * @Date: 2020/5/13 22:48
     * @ACTION:
     * @param request:
     * @param response:
     * @return: boolean
     **/
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return Boolean.FALSE;
    }

    private void out(ServletResponse hresponse, Map<String, String> resultMap)
            throws IOException {
        try {
            hresponse.setCharacterEncoding("UTF-8");
            PrintWriter out = hresponse.getWriter();
            out.println(JSONObject.toJSONString(resultMap));
            out.flush();
            out.close();
        } catch (Exception e) {
            log.info("-->CheckSessionControlFilter.class 输出JSON异常，可以忽略。");
        }
    }
}
